<template>
  <div class="provider-node-form">
    <h4> {{ title }} </h4>
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item v-if="nodeType === 'providerServices'" label="系统名称:" prop="systemId">
        <el-select v-model="form.systemId" clearable placeholder="请选择系统名称" @change="systemIdChange">
          <el-option
            v-for="(item, index) in systemIdList"
            :key="index"
            :label="item.systemName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="服务名称:" prop="componentId">
        <el-select v-model="form.componentId" clearable placeholder="请选择服务名称" @change="componentIdChange">
          <el-option
            v-for="(item, index) in componentIdList"
            :key="index"
            :label="item.serviceName"
            :value="item.id"
            :disabled="item.disabled"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="服务编号:">
        {{ interfaceForm.serviceCode }}
      </el-form-item>

      <el-form-item label="接口方式:">
        {{ getDictText('interface_type', interfaceForm.interfaceType) }}
      </el-form-item>

      <el-form-item label="接口地址:">
        {{ interfaceForm.interfaceAddress }}
      </el-form-item>

      <el-form-item label="接口协议:">
        {{ getDictText('interface_protocol', interfaceForm.interfaceProtocol) }}
      </el-form-item>

      <el-form-item label-width="140px">
        <template slot="label">
          <span class="custom-label"> 是否为token接口 </span>
        </template>
      </el-form-item>
      <el-form-item prop="isToken" label-width="20px">
        <el-switch
          v-model="form.isToken"
          active-text="开"
          active-value="Y"
          active-color="#87D068"
          inactive-text="关"
          inactive-value="N"
          inactive-color="#D9001B"
        />
      </el-form-item>

      <el-form-item label-width="80px">
        <template slot="label">
          <span class="custom-label"> 重试规则 </span>
        </template>
      </el-form-item>
      <el-form-item label="是否启用:" prop="retryFlag">
        <el-switch
          v-model="form.retryFlag"
          active-text="开"
          active-value="Y"
          active-color="#87D068"
          inactive-text="关"
          inactive-value="N"
          inactive-color="#D9001B"
        />
      </el-form-item>

      <el-form-item v-if="form.retryFlag === 'Y'" label="重试次数:" prop="retryNum">
        <el-input-number v-model="form.retryNum" :min="0" :controls="false" />
      </el-form-item>

      <el-form-item v-if="form.retryFlag === 'Y'" label="重试时间间隔(秒):" prop="retryTime" label-width="140px">
        <el-input-number v-model="form.retryTime" :min="0" :controls="false" />
      </el-form-item>

      <el-form-item label-width="80px">
        <template slot="label">
          <span class="custom-label"> 请求信息 </span>
        </template>
      </el-form-item>

      <el-form-item label-width="0">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="请求头" name="1" />
          <el-tab-pane label="请求参数" name="2" />
          <!-- v-if="interfaceForm.interfaceProtocol == '2'"  -->
          <el-tab-pane label="restful风格" name="3" />
        </el-tabs>

        <!-- 请求头/请求参数 键值对 -->
        <div v-if="activeName !== '3'">
          <el-button size="small" type="text" @click="addLine"> 添加行 </el-button>
          <el-button size="small" type="text" class="text-del-btn" @click="delLine"> 删除行 </el-button>
          <el-table
            border
            :data="tableData"
            style="margin-top: 10px;width: 100%"
            :row-class-name="rowClassName"
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              type="selection"
              width="45"
            />
            <el-table-column
              prop="key"
              label="key"
            >
              <template slot-scope="{ row }">
                <el-input v-model="row.key" />
              </template>
            </el-table-column>
            <el-table-column
              prop="value"
              label="value"
            >
              <template slot-scope="{ row }">
                <el-input v-model="row.value" />
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- restful风格 -->
        <el-input v-else v-model="form.requestField.restful" placeholder="" />
      </el-form-item>

      <el-form-item label-width="0">
        <el-button size="small" @click="cancelForm">取消</el-button>
        <el-button size="small" type="primary" @click="submitForm('form')">确定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getProviderSystemInfoApi, getInterfaceListApi } from '@/api/serviceManage/serviceAdaptation'
import { pageApi } from '@/api/serviceManage/requestPartyServiceManage'
import dictMixin from '@/utils/mixins/dict'

import _ from 'lodash'
export default {
  mixins: [
    dictMixin(['interface_type', 'interface_protocol'])
  ],
  props: {
    requestSystemId: {
      type: String,
      default: ''
    },

    title: {
      type: String,
      default: ''
    },

    nodeType: {
      type: String,
      default: ''
    },

    providerHasSelect: {
      type: Array,
      default: () => []
    }
  },

  data () {
    return {
      tableData: [],
      activeName: '1',
      form: {
        systemId: '',
        componentId: '',
        componentName: '',
        retryFlag: 'N',
        isToken: 'N',
        retryNum: void 0,
        retryTime: void 0,
        requestField: {
          header: '[]',
          request: '[]',
          restful: ''
        }
      },
      interfaceForm: {
        interfaceType: '',
        serviceCode: '',
        interfaceAddress: '',
        interfaceProtocol: ''
      },
      rules: {
        systemId: { required: true, message: '请选择系统', trigger: 'change' },
        componentId: { required: true, message: '请选择接口', trigger: 'change' },
        retryNum: { required: true, message: '请选择重试次数', trigger: 'change' },
        retryTime: { required: true, message: '请选择重试间隔', trigger: 'change' }
      },

      // 系统列表
      systemIdList: [],
      // 接口列表
      componentIdList: [],
      // 表格选中的数据
      multipleSelection: []
    }
  },

  watch: {
    tableData: {
      handler (val) {
        if (this.activeName === '1') {
          this.form.requestField.header = JSON.stringify(this.tableData)
        } else if (this.activeName === '2') {
          this.form.requestField.request = JSON.stringify(this.tableData)
        }
      },
      deep: true
    }
  },

  created () {
    /* 提供方服务获取系统，请求方服务直接获取接口 */
    if (this.nodeType === 'providerServices') {
      // 获取系统
      getProviderSystemInfoApi({
        systemId: this.requestSystemId
      }).then(({ code, data }) => {
        if (code === '00000') {
          this.systemIdList = data
        }
      })
    }
  },

  methods: {
    // 初始化form
    initForm (data) {
      const _data = data
      if (data && data.componentId) {
        this.form = data
        this.tableData = JSON.parse(data.requestField.header)

        if (data.systemId) {
          this.systemIdChange(data.systemId, data.componentId)
        }
      } else {
        this.form = {
          systemId: '',
          componentId: '',
          componentName: '',
          retryFlag: 'N',
          isToken: 'N',
          retryNum: void 0,
          retryTime: void 0,
          requestField: {
            header: '[]',
            request: '[]',
            restful: ''
          }
        }
      }
      if (this.nodeType === 'supplicantServices') {
        pageApi({
          pageNo: 1,
          pageSize: -1,
          manageType: 1
        }).then(({ code, data }) => {
          if (code === '00000') {
            this.componentIdList = data.rows
            if (_data && _data.componentId) {
              const item = data.rows.filter(item => item.id === _data.componentId)[0]
              this.setInterfaceForm(item)
            }
          }
        })
      }
    },

    // 切换系统
    systemIdChange (data, componentId) {
      if (data) {
        getInterfaceListApi({
          provideId: data,
          requestId: this.requestSystemId
        }).then(({ code, data }) => {
          if (code === '00000') {
            this.componentIdList = data.map(item => ({
              ...item,
              disabled: JSON.stringify(this.providerHasSelect).indexOf(item.id) > -1
            }))

            if (componentId) {
              const item = data.filter(item => item.id === componentId)[0]
              this.setInterfaceForm(item)
            }
          }
        })
      } else {
        this.comidentIdList = []
        this.form.componentId = ''
        this.setInterfaceForm()
      }
    },

    // 设置服务编号/接口方式/接口地址/接口协议
    setInterfaceForm (data) {
      this.interfaceForm = {
        interfaceType: data ? data.interfaceType : '',
        serviceCode: data ? data.serviceCode : '',
        interfaceAddress: data ? data.interfaceAddress : '',
        interfaceProtocol: data ? data.interfaceProtocol : ''
      }
      this.form.componentName = data ? data.serviceName : ''
    },

    // 切换服务
    componentIdChange (data) {
      const item = this.componentIdList.filter(item => item.id === data)[0]
      this.setInterfaceForm(item)
    },

    // 确定
    submitForm (formName) {
      const has_$ = /\$/
      const restful = /^\$\{([^}\s]+)\}$/

      const judgRequestInfo = (data, msg) => {
        return new Promise((resolve, reject) => {
          for (let index = 0; index < data.length; index++) {
            const item = data[index]
            if (!item.key || !item.value) {
              this.$message.warning(`请完善${msg}！`)
              reject()
            }

            if (has_$.test(item.value) && !restful.test(item.value)) {
              this.$message.warning(`${msg}中，restful风格的值请填写正确！`)
              reject()
            }
          }

          resolve()
        })
      }
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          if (this.form.requestField.header !== '[]') {
            await judgRequestInfo(JSON.parse(this.form.requestField.header), '请求头')
          }
          if (this.form.requestField.request !== '[]') {
            await judgRequestInfo(JSON.parse(this.form.requestField.request), '请求参数')
          }
          if (this.form.requestField.restful !== '') {
            if (this.form.requestField.restful.charAt(0) !== '/') {
              return this.$message.warning(`restful风格请以 / 开头！`)
            }

            const array = this.form.requestField.restful.split('/')
            for (let index = 0; index < array.length; index++) {
              const item = array[index]
              if (item) {
                if (has_$.test(item) && !restful.test(item)) {
                  return this.$message.warning(`restful风格请填写正确！`)
                }
              }
            }
          }
          this.$emit('nodeForm', this.form)
        }
      })
    },
    // 取消
    cancelForm () {
      this.$emit('nodeForm')
    },

    // 表格添加序号
    rowClassName ({ row, rowIndex }) {
      // 把每一行的索引放进row
      row.index = rowIndex
    },

    // 添加行按钮
    addLine () {
      this.tableData.push({
        key: '',
        value: ''
      })
    },

    // 删除行按钮
    delLine () {
      if (this.multipleSelection.length === 0) {
        return this.$message.warning('请选择要删除的行')
      }
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableData = this.tableData.filter(item => !this.multipleSelection.map(item => item.index).includes(item.index))
      })
    },

    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    // 请求信息切换
    handleClick() {
      if (this.activeName === '1') {
        this.tableData = _.cloneDeep(JSON.parse(this.form.requestField.header))
      } else if (this.activeName === '2') {
        this.tableData = _.cloneDeep(JSON.parse(this.form.requestField.request))
      }
    }
  }
}
</script>
